package org.gwtEss.client;

import java.util.HashMap;
import java.util.Map;

import org.gwtEss.link.LabelLink;
import org.gwtEss.other.SimpleTextPanel;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.Widget;

public class LogPanel extends Composite{
//	DisclosurePanel mainPanel = new DisclosurePanel("Log messages");
//	Label lab = new Label();
	DialogBox db = new DialogBox(false, false);
	String txt = "";
	Tree msgTree; 
	TreeItem debug, error, msg; 
	Map<String, TreeItem> treeItemMap = new HashMap<String, TreeItem>(); 
	public LogPanel() {
//		mainPanel.setContent(txtW);
		msgTree = new Tree();
		msgTree.addItem(debug = createMsgNode("debug"));
		msgTree.addItem(error = createMsgNode("error"));
		msgTree.addItem(msg = createMsgNode("msg"));
		db.setText("Log");
		db.setWidget(new ScrollPanel(msgTree){
			{
				setSize("200px", "300px");
			}
		});
//		db.setSize("80px", "200px");
		LabelLink t = new LabelLink("Log messages", new ClickHandler(){
			private boolean hidden = true; 
			public void onClick(ClickEvent event) {
				if (hidden)
					db.show();
				else
					db.hide();
				hidden = !hidden;
//				db.setPopupPosition(event.getNativeEvent().getClientX(), event.getNativeEvent().getClientY());
			}
			
		});
		
		initWidget(t);
	}
	private void addItem(final TreeItem node, final String txt){
		DeferredCommand.addCommand(new Command(){
			public void execute() {
				node.addItem(txt);
			}
		});		
	}
	public void debug(final String str){
		addItem(debug, str);
	}
	public void error(final String str){
		addItem(error, str);
	}
	public void msg(final String str){
		addItem(msg, str);
	}
	private TreeItem createMsgNode(final String nodeName){
		final TreeItem treeItem = new TreeItem(nodeName);
		treeItem.setWidget(new HorizontalPanel(){
			{
				setSpacing(2);
				add(new SimpleTextPanel(nodeName));
				add(new LabelLink("clear", new ClickHandler(){

					public void onClick(ClickEvent event) {
						treeItem.removeItems();
					}
					
				}));
			}
		}); 
		return treeItem;
	}
	public void custom(final String groupName, final String str){
		TreeItem tItem;
		tItem = treeItemMap.get(groupName);
		if (tItem == null){
			tItem = createMsgNode(groupName);
//			createMsgNode(groupName, treeItemMap.get(groupName));
			
			treeItemMap.put(groupName, tItem);
			msgTree.addItem(tItem);
		}
		addItem(tItem, str);
	}
}
